package middleware

import (
	"errors"
	"github.com/gin-gonic/gin"
	jwt2 "go-mall/pkg/jwt"
)

//var jwtUtil = jwt2.UtilJWT{}

func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.Request.Header.Get("Authorization")
		if token == "" {
			c.JSON(200, gin.H{"code": 400001, "reload": true, "msg": "未携带token！"})
			c.Abort()
			return
		}
		j := jwt2.NewJWT()
		// parseToken 解析token包含的信息
		claims, err := j.ParseToken(token)
		if err != nil {
			if errors.Is(err, jwt2.TokenExpired) {
				//token 令牌已过期 需要重新登陆签发token
				c.JSON(200, gin.H{"code": 401, "reload": true, "msg": err.Error()})
				c.Abort()
				return
			}

			c.JSON(200, gin.H{"code": 400002, "reload": true, "msg": err.Error()})
			c.Abort()
			return
		}
		c.Set("claims", claims)
		c.Next()
	}
}
